package guda.stark.web.action;

import guda.grape.autogen.common.page.BizResult;
import guda.grape.mvc.form.Form;
import guda.grape.mvc.security.auth.AuthGrant;
import guda.stark.biz.AdminBiz;
import guda.stark.biz.form.LoginForm;
import guda.stark.dal.dataobject.AdminDO;
import guda.stark.web.security.AuthUser;
import guda.stark.web.security.DefaultAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

/**
 * Created by well on 15/10/15.
 */
@Controller
public class LoginAction {

    @Autowired
    private AdminBiz adminBiz;

    @RequestMapping(value = "login.htm", method = RequestMethod.GET)
    public String login(HttpServletRequest request, ModelMap modelMap, LoginForm loginForm,
                        BindingResult result, Map<String, Object> model) {
        if(AuthUser.isLogin()){
            return "redirect:index.htm";
        }
        return "login.vm";

    }

    @Form
    @RequestMapping(value = "login.htm", method = RequestMethod.POST)
    public String doLogin(HttpServletRequest request, ModelMap modelMap,@Valid LoginForm loginForm,
                        BindingResult result, Map<String, Object> model) {
        if(result.hasErrors()){
            return "login.vm";
        }
        BizResult login = adminBiz.login(loginForm);
        if(!login.success){
            result.rejectValue("username","usernameOrPasswordError","用户名或者密码错误");
            return "login.vm";
        }
        AdminDO admin = (AdminDO)login.data.get("admin");
        AuthUser authUser = new AuthUser();
        authUser.setUserId(admin.getAdminId());
        authUser.setLoginName(admin.getLoginName());
        authUser.setRoles(new String[]{admin.getRoleName()});
        AuthUser.setCurrentUser(authUser);
        request.getSession().setAttribute(DefaultAuth.sessionKey,authUser);
        return "redirect:index.htm";

    }

    @RequestMapping(value = "loginOut.htm", method = RequestMethod.GET)
    public String loginOut(HttpServletRequest request, ModelMap modelMap, Map<String, Object> model) {
        AuthUser.cleanThreadLocal();
        request.getSession().removeAttribute(DefaultAuth.sessionKey);
        return "redirect:login.htm";

    }
}
